package com.ktjiaoyu.demo;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @ClassName : UserServiceLogger
 * @Description :
 * @Author : Lzz
 * @Date: 2023/9/27 09:45:42
 */
@Component("serviceLogger")
@Aspect
public class UserServiceLogger {

    private Logger logger = Logger.getLogger(UserServiceLogger.class);

    @Pointcut("execution(* com.ktjiaoyu.demo..*.save(..))")
    public void pointcut(){}

    /**
     * 前置增强
     * @param joinPoint
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName());
    }

    /**
     * 环绕通知
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName());
        try {
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                System.out.println("方法参数："+args[i]);
            }
            Object result = joinPoint.proceed();        //执行目标方法并获得返回值
            return result;
        } catch (Throwable e){
            logger.error("执行方法发生异常"+e);
            throw e;
        } finally {
            logger.info("执行方法结束！");
        }

    }


    /**
     * 返回通知
     * @param joinPoint
     * @param obj
     */
    @AfterReturning(value = "execution(* com.ktjiaoyu.demo..*.save(..))",returning = "obj")
    public void afterRuning(JoinPoint joinPoint,Object obj){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()+"，返回："+obj);
    }

    /**
     * 异常抛出通知
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value = "execution(* com.ktjiaoyu.demo..*.save(..))",throwing = "ex")
    public void throwError(JoinPoint joinPoint,RuntimeException ex){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()
                +"方法，发生异常："+ex);
    }

    /**
     * 最终通知
     */
    @After("execution(* com.ktjiaoyu.demo..*.save(..))")
    public void after(JoinPoint joinPoint){
        logger.info("调用"+joinPoint.getTarget()+"的"+joinPoint.getSignature().getName()
                +"方法结束了！！");
    }

}
